<template>
  <div>
        <div v-if="returnOrderInfo.returnType==1">
            <el-empty description="仅退款，无需退货"></el-empty>
        </div>
          <div  v-else>
            <div style="text-align:right;margin-bottom:5px;">
            <el-button type="warning" v-if="returnOrderInfo.returnType!==1 && canModify" @click="toOrderDetail">添加退货产品</el-button>
          </div>
          <el-table  :key="talbekey" show-summary    class="wp-product-table" :summary-method="getSummaries" :data="returnProductList">
                <el-table-column label="产品名称" width="120" prop="productName" show-overflow-tooltip></el-table-column>
                <el-table-column label="产品类型" prop="productTypeName"></el-table-column>
                <el-table-column label="产品型号"  prop="productModel" show-overflow-tooltip></el-table-column>
                <el-table-column label="产品单位" prop="unit"></el-table-column>
                <el-table-column :label="returnOrderOption.productLabel+'数量'" prop="productNum"></el-table-column>
                <el-table-column :label="returnOrderOption.productLabel+'金额'" prop="discountTotalAmount">
                  <template slot-scope="scope">
                      {{scope.row.discountTotalAmount||'--'}}
                  </template>
                </el-table-column>
                <el-table-column label="退货数量"  width="150" prop="returnNum">
                    <template slot-scope="scope">
                      <el-input-number v-if="scope.row.editFlag" size="mini" :min="1" :max="scope.row.productNum" v-model="scope.row.returnNum"  placeholder="请填写"></el-input-number>
                      <span v-else>{{scope.row.returnNum}}</span>
                    </template>
                </el-table-column>
                <el-table-column  label="退款金额" width="150" prop="returnAmount">
                   <template slot-scope="scope">
                      <el-input-number v-if="scope.row.editFlag" :disabled="returnOrderInfo.returnType!==2" size="mini" :min="0"   v-model="scope.row.returnAmount"  placeholder="请填写"></el-input-number>
                       <span v-else>{{scope.row.returnAmount}}</span>
                    </template>
                </el-table-column>
                <el-table-column  label="退货原因"  width="150" prop="returnReason">
                    <template slot-scope="scope">
                        <el-input  v-if="scope.row.editFlag" v-model="scope.row.returnReason" placeholder="填写退货原因"></el-input>
                        <span v-else>{{scope.row.returnReason}}</span>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" align="center" width="120" label="操作" v-if="canModify">
                     <template slot-scope="scope">
                         <el-link type="info"  v-if="scope.row.editFlag" @click="toCancel(scope.row)">取消编辑</el-link>
                         <el-link :type="scope.row.editFlag?'success':'warning'"  @click="toEdit(scope.row)">{{scope.row.editFlag?'确定':'编辑'}}</el-link>
                         <el-link type="danger"  v-if="!scope.row.editFlag" @click="deleteReturnProduct(scope.$index,scope.row)" >删除</el-link>
                     </template>
                </el-table-column>
            </el-table>
        <el-dialog  append-to-body :title="returnOrderOption.label+'产品信息'" :visible.sync="visibleOrderDetail">
            <el-table :data="orderDetailList" ref="returnProductRef">
              <el-table-column type="selection"  :selectable="checkSelect" width="50"></el-table-column>
              <el-table-column label="产品名称" show-overflow-tooltip prop="productName"></el-table-column>
              <el-table-column label="产品类型" prop="productTypeName"></el-table-column>
              <el-table-column label="产品型号"  show-overflow-tooltip prop="productModel"></el-table-column>
              <el-table-column label="产品单位" prop="unit"></el-table-column>
              <el-table-column :label="returnOrderOption.productLabel+'数量'" :prop="returnOrderOption.productNumKey"></el-table-column>
              <el-table-column :label="returnOrderOption.productLabel+'金额'" prop="discountTotalAmount">

              </el-table-column>
            </el-table>
             <div slot="footer" class="wp-footer__box">
                <el-button type="" @click="visibleOrderDetail=false">取消</el-button>
                <el-button type="success" @click="selectReturnProduct">确定</el-button>
            </div>
        </el-dialog>
        </div>
  </div>
</template>
<script>
import returnOrder from '@/api/eims/returnOrderAPI'
import salesOrder from '@/api/eims/sales/salesOrderAPI'
import purchaseOrder from '@/api/eims/purchase/orderAPI'
import {toDecimal} from '@/utils'
export default {
  props: {
    type: String,
    param: Object
  },
  components: {},
  watch: {
    param: {
      handler (val, ov) {
        this.canModify = val.status === 0 || val.status === 2
        this.returnOrderInfo = {...val}
      },
      deep: true,
      immediate: true
    },
    totalSumAmount (val, nval) {
      console.log('totalSumAmount', val, nval)
      // this.returnOrderInfo.returnTotalAmount = val
      this.$emit('update:param', this.returnOrderInfo)
    }
  },
  computed: {
    returnOrderOption () {
      const option = {}
      if (this.type === 'purchaseOrder') {
        option.lableKey = 'purchaseNo'
        option.valueKey = 'purchaseNo'
        option.type = 'purchaseOrder'
        option.placeholder = '+添加采购订单'
        option.label = '采购订单'
        option.productLabel = '采购'
        option.productNumKey = 'purchaseNum'
        option.relationNameKey = 'supplierName'
        option.relationCodeKey = 'supplierCode'
        option.relationDetailNoKey = 'purchaseDetailNo'
        option.relationNameLabel = '经销商'
        option.queryProductFun = (orderNo, cb) => {
          this.getPurchaseOrderDetialList(orderNo, cb)
        }
      } else {
        option.lableKey = 'orderNo'
        option.valueKey = 'orderNo'
        option.type = 'salesOrder'
        option.placeholder = '+添加销售订单'
        option.label = '销售订单'
        option.productLabel = '销售'
        option.productNumKey = 'productNum'
        option.relationNameKey = 'customerName'
        option.relationCodeKey = 'customerCode'
        option.relationDetailNoKey = 'orderDetailNo'
        option.relationNameLabel = '客户'
        option.queryProductFun = (orderNo, cb) => {
          this.getSalesOrderProductList(orderNo, cb)
        }
      }
      return option
    }
  },
  data () {
    return {
      talbekey: '',
      canModify: false,
      returnOrderInfo: {},
      returnProductList: [],
      orderDetailList: [],
      visibleOrderDetail: false,
      totalSumAmount: null
    }
  },
  mounted () {
    this.getReturnOrderDetialList(this.param.returnNo, this.param.returnOrderType)
  },
  methods: {
    reloadList () {
      this.talbekey = Math.random()
    },
    refreshReturnTotalAmount () {
      this.returnOrderInfo.returnTotalAmount = this.totalSumAmount
      this.$emit('update:param', this.returnOrderInfo)
    },
    toCancel (row) {
      row.editFlag = false
      if (row.original) {
        row.returnAmount = row.original.returnAmount
        row.returnNum = row.original.returnNum
      }
      this.reloadList()
    },
    toEdit (row) {
      row.original = {...row}
      if (row.editFlag) {
        const params = {...row}
        params.returnNo = this.param.returnNo
        if (!params.returnNum || params.returnNum <= 0) {
          this.$msgBox.error('退货数量不能为空')
          return
        }
        if (row.id) {
          returnOrder.updateReturnOrderDetailAPI(params).then(res => {
            if (res.code === 0) {
              row.editFlag = !row.editFlag
              this.reloadList()
              this.refreshReturnTotalAmount()
              this.$emit('editAfter', params.returnNo)
            }
          })
        } else {
          returnOrder.saveReturnOrderDetailAPI(params).then(res => {
            if (res.code === 0) {
              row.editFlag = !row.editFlag
              this.reloadList()
              this.refreshReturnTotalAmount()
              this.$emit('editAfter', params.returnNo)
            }
          })
        }
      } else {
        row.editFlag = !row.editFlag
        this.reloadList()
      }
    },
    getReturnOrderDetialList (returnNo, returnOrderType) {
      returnOrder.getReturnOrderDetailListAPI(returnNo, returnOrderType).then(res => {
        this.returnProductList = res.data || []
      })
    },
    getPurchaseOrderDetialList (orderNo, cb) {
      purchaseOrder.getOrderProductListAPI(orderNo).then(res => {
        cb(res)
      })
    },
    getSalesOrderProductList (orderNo, cb) {
      salesOrder.getOrderProductListAPI(orderNo).then(res => {
        cb(res)
      })
    },
    toOrderDetail () {
      if (!this.returnOrderInfo.relationOrderNo) {
        this.$msgBox.error(`请选择${this.returnOrderOption.label}`)
        return
      }
      this.visibleOrderDetail = true
      this.returnOrderOption.queryProductFun(this.returnOrderInfo.relationOrderNo, res => {
        this.orderDetailList = res.data || []
      })
    },
    selectReturnProduct () {
      const returnProduct = this.$refs.returnProductRef.selection
      if (!returnProduct || returnProduct.length <= 0) {
        this.$msgBox.error(`请选择退货产品`)
        return
      }
      const selectReturnProductList = returnProduct.map(item => {
        const productInfo = {}
        productInfo.discountTotalAmount = item.discountTotalAmount
        productInfo.productCode = item.productCode
        productInfo.productName = item.productName
        productInfo.productTypeName = item.productTypeName
        productInfo.productType = item.productType
        productInfo.productModel = item.productModel
        productInfo.unit = item.unit
        productInfo.editFlag = true
        productInfo.relationDetailNo = item[this.returnOrderOption.relationDetailNoKey]
        productInfo.productNum = item[this.returnOrderOption.productNumKey]
        return productInfo
      })
      this.returnProductList = [...selectReturnProductList, ...this.returnProductList]
      this.$refs.returnProductRef.clearSelection()
      this.visibleOrderDetail = false
    },
    getSummaries (param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = ''
          return
        }
        const values = data.map((item) => Number(item[column.property]))
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = Math.round(sums[index] * 100) / 100
        }
      })
      this.totalSumAmount = toDecimal(sums[7]||0)
      return sums
    },
    checkSelect (row, index) {
      if (this.returnProductList) {
        const productInfo = this.returnProductList.find(item => {
          return item.productCode === row.productCode
        })
        return (
          !productInfo || Object.getOwnPropertyNames(productInfo).length === 0
        )
      }
      return true
    },
    deleteReturnProduct (index, row) {
      if (this.returnOrderInfo.returnType !== 1 && this.returnProductList.length <= 1) {
        this.$msgBox.error('退货产品不能为空')
        return
      }
      this.$msgBox.confirm(
        '确认删除退款产品' + (row.productName || '') + '?',
        () => {
          if (row.id) {
            returnOrder.deleteReturnOrderDetailInfoAPI(row.id).then(res => {
              if (res.code === 0) {
                this.returnProductList.splice(index, 1)
                this.refreshReturnTotalAmount()
                this.$emit('editAfter', this.param.returnNo)
              }
            })
          } else {
            this.returnProductList.splice(index, 1)
          }
        }
      )
    }
  }
}
</script>

<style lang="scss" scoped>
.wp-product-table >>> .el-table__footer-wrapper,
.wp-product-table >>> .el-table__footer {
  display: none;
}
</style>
